<?php declare(strict_types=1);

namespace app\common\service;

use app\common\model\Article;
use app\common\model\ArticleCategory;
use think\db\exception\DbException;

class ArticleService
{
    /**
     * 获取分类下的文章
     * @param int|array|null $categoryId
     * @param array $map 条件
     * @param int $pageSize
     * @param mixed $args
     * @return void
     * @throws DbException
     */
    public function getArticleByCategory(int|array|null $categoryId, array $map, $pageSize = 10, ...$args)
    {
        $model = new Article();
        $items = $model->field(['id','name','category_id','keywords','description','thumb_url','is_rec','status','sort','add_like','views','update_time','editor'])
            ->where('status', 1)
            ->where(function ($query) use ($categoryId, $map, $args) {
                if($categoryId){
                    if (is_array($categoryId)) {
                        $query->whereIn('category_id', $categoryId);
                    } else {
                        $query->where('category_id', $categoryId);
                    }
                }
                if ($map) {
                    foreach ($map as $k=>$v) {
                        $query->where($k, $v);
                    }
                }
                // 可变参数
                if ($args) {
                    foreach ($args as $arg) {
                        if (!empty($arg)) {
                            $query->where('name|keywords|description', 'like', $arg. '%');
                        }
                    }
                }
            })
            ->order(['sort'=>'desc','id'=>'desc'])
            ->paginate($pageSize)
            ->each(function($item) {
                $item['category_name'] = $this->getCategoryName($item->category_id);
                return $item;
            });
        return $items;
    }

    /**
     * 获取记录
     * @param array $map 条件
     * @param array $paginate 分页
     * @param mixed $args
     * @return void
     * @throws DbException
     */
    public function getDatas(array $map, array $paginate = ['list_rows' => 10], ...$args)
    {
        $model = new Article();
        $items = $model->field(['id','name','category_id','keywords','description','thumb_url','is_rec','status','sort','add_like','views','update_time','editor'])
            ->where('status', 1)
            ->where(function ($query) use ($map, $args) {
                if ($map) {
                    foreach ($map as $k=>$v) {
                        $query->where($k, $v);
                    }
                }
                // 可变参数
                if ($args) {
                    foreach ($args as $arg) {
                        if (!empty($arg)) {
                            $query->where('name|keywords|description', 'like', $arg. '%');
                        }
                    }
                }
            })
            ->order(['sort'=>'desc','id'=>'desc'])
            ->paginate($paginate, false)
            ->each(function($item) {
                $item['category_name'] = $this->getCategoryName($item->category_id);
                return $item;
            });
        return $items;
    }

    /**
     * 获取指定分类下的文章
     * @param int|string|array $categoryId
     * @return void
     * @throws DbException
     */
    public function getArticleBy(int|string|array $categoryId)
    {
        $categoryModel = new ArticleCategory();
        $model = new Article();
        $items = $categoryModel->field('id,name')
            ->where(['status'=>1])
            ->where(function ($query) use ($categoryId) {
                if($categoryId){
                    if (is_int($categoryId)) {
                        $query->where('id', $categoryId);
                    } else {
                        $query->whereIn('id', $categoryId);
                    }
                }
            })
            ->order(['sort'=>'asc'])
            ->select()
            ->each(function($item) use($model){
                $item['article_list'] = $model->field('id,name,category_id,thumb_url')
                                            ->where(['category_id'=>$item->id, 'status'=>1, 'is_rec'=>1])
                                            ->order(['sort'=>'desc'])
                                            ->limit(6)
                                            ->select();
                return $item;
            });

        return $items;
    }

    /**
     * 获取指定条件下的文章
     * @param array $where
     * @param int $pageSize
     * @return array|Article[]|\think\Collection
     * @throws DbException
     */
    public function getArticleByWhere(array $where, int $pageSize = 10)
    {
        $model = new Article();
        return $model->field('id,name,category_id,thumb_url,description,views,update_time')
            ->where($where)
            ->order(['sort'=>'desc', 'update_time'=>'desc'])
            ->limit($pageSize)
            ->select();
    }

    /**
     * 获取推荐文章
     * @param array $where
     * @param int $pageSize
     * @return Article[]|array|\think\Collection
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRecArticles(array $where, int $pageSize = 10)
    {
        $model = new Article();
        $items = $model->field('id,name,category_id,description,views,update_time')
            ->where($where)
            ->order(['sort'=>'desc', 'update_time'=>'desc'])
            ->paginate($pageSize);
        return $items;
    }

    /**
     * 获取指定类型的文章分类
     * @param int $type
     * @return ArticleCategory[]|array|\think\Collection
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCategoryTypes(int $type = 1): \think\Collection|array
    {
        $categoryModel = new ArticleCategory();
        return $categoryModel->field('id,name,type')
            ->where(['status'=>1, 'type'=>$type])
            ->order(['sort'=>'asc'])
            ->select();
    }

    /**
     * 文章详情
     * @param $id
     * @return void
     */
    public function getArticleDetail($id)
    {
        $model = new Article();
        $item = $model->where('status', 1)->find($id);
        if ($item) {
            $item->category_name = $this->getCategoryName($item->category_id);
        }

        return $item;
    }

    /**
     * 获取上一篇
     * @param $id
     * @param $categoryId
     * @return array
     */
    public function getPrevArticle($id, $categoryId = 0)
    {
        $map[] = ['status', '=', 1];
        if ($categoryId) {
            $map[] = ['category_id', '=', $categoryId];
        }
        $model = new Article();
        $item = $model->field('id,category_id,name')->where($map)->where('id', '<', $id)->findOrEmpty()->toArray();
        if (!$item) {
            return [];
        }

        return $item;
    }

    /**
     * 获取下一篇
     * @param $id
     * @param $categoryId
     * @return array
     */
    public function getNextArticle($id, $categoryId = 0)
    {
        $map[] = ['status', '=', 1];
        if ($categoryId) {
            $map[] = ['category_id', '=', $categoryId];
        }
        $model = new Article();
        $item = $model->field('id,category_id,name')->where($map)->where('id', '>', $id)->findOrEmpty()->toArray();
        if (!$item) {
            return [];
        }

        return $item;
    }

    /**
     * 更新浏览量
     * @param $id
     * @return array
     */
    public function views($id)
    {
        $model = new Article();


        return $model->where( 'id', $id)->setInc('views');
    }

    /**
     * 获取分类名称
     * @param $categoryId
     * @return void
     */
    public function getCategoryName($categoryId)
    {
        $model = new ArticleCategory();
        return $model->where('id', $categoryId)->value('name') ?? '';
    }
}